<template>
  <div class="home-container">
    <el-card class="game-card">
      <template #header>
        <div class="card-header">
          <h2>AI猜画游戏</h2>
          <el-button type="primary" @click="handleRecognize" :loading="isRecognizing">
            <el-icon><Search /></el-icon>
            开始识别
          </el-button>
        </div>
      </template>
      
      <DrawingCanvas ref="drawingCanvasRef" />
      
      <div v-if="recognitionResult || imageDescription" class="result-container">
        <template v-if="recognitionResult">
          <h3>识别结果：</h3>
          <div class="result-tags">
            <el-tag
              v-for="(result, index) in recognitionResult"
              :key="index"
              class="result-tag"
              :type="index === 0 ? 'success' : ''"
            >
              {{ result.label }} ({{ (result.confidence * 100).toFixed(1) }}%)
            </el-tag>
          </div>
        </template>
        
        <template v-if="imageDescription">
          <h3 class="description-title">图片描述：</h3>
          <p class="description-text">{{ imageDescription }}</p>
        </template>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import DrawingCanvas from '../components/DrawingCanvas.vue'
import { ElMessage } from 'element-plus'

const drawingCanvasRef = ref()
const isRecognizing = ref(false)
interface RecognitionResult {
  label: string
  confidence: number
}

interface ApiResponse {
  results: RecognitionResult[]
  description: string
}

const recognitionResult = ref<RecognitionResult[] | null>(null)
const imageDescription = ref<string | null>(null)

// 获取画布数据并发送到后端进行识别
const handleRecognize = async () => {
  if (!drawingCanvasRef.value) {
    ElMessage.error('画布未准备就绪')
    return
  }

  isRecognizing.value = true
  try {
    const canvas = drawingCanvasRef.value
    // 将画布内容转换为base64格式的图片数据
    const imageData = canvas.toDataURL('image/png')
    // 将base64图片数据转换为Blob
    const base64Data = imageData.split(',')[1]
    const blob = await fetch(`data:image/png;base64,${base64Data}`).then(res => res.blob())
    
    // 创建FormData对象
    const formData = new FormData()
    formData.append('image', blob, 'drawing.png')
    
    // 发送图片数据到后端API
    const response = await fetch('/api/drawing/recognize', {
      method: 'POST',
      body: formData
    })

    if (!response.ok) {
      throw new Error(`识别请求失败: ${response.status}`)
    }

    const data: ApiResponse = await response.json()
    recognitionResult.value = data.results
    imageDescription.value = data.description
  } catch (error) {
    ElMessage.error('识别失败，请重试')
  } finally {
    isRecognizing.value = false
  }
}
</script>

<style scoped>
.home-container {
  max-width: min(1000px, 100%);
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media screen and (max-width: 768px) {
  .home-container {
    padding: 10px;
  }
}

.game-card {
  background-color: #f5f7fa;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

@media screen and (max-width: 480px) {
  .card-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .card-header h2 {
    text-align: center;
  }
  
  .card-header .el-button {
    width: 100%;
  }
}

.card-header h2 {
  margin: 0;
  color: #303133;
}

.result-container {
  margin-top: 20px;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  overflow-x: auto;
}

@media screen and (max-width: 480px) {
  .result-container {
    padding: 12px;
  }
}

.result-container h3 {
  margin: 0 0 12px;
  color: #303133;
}

.result-tag {
  margin: 0;
}

.result-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.description-container {
  margin-top: 20px;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
}

.description-container h3 {
  margin: 0 0 12px;
  color: #303133;
}

.description-text {
  margin: 0;
  line-height: 1.6;
  color: #606266;
  font-size: 14px;
}
</style>